import { BlockLocationIterator, BlockVolume, Vector3 } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { GameComponent } from "@sapi-game/main";
import { PKParkourControlState } from "../pkState";

export class EndPointFinder extends GameComponent<PKParkourControlState> {
    private startPoints: Vector3[] = [];

    override onAttach(): void {}

    getPoints() {
        return this.startPoints;
    }

    async search(volume: BlockVolume, batchSize = 1024) {
        const iterator = volume.getBlockLocationIterator();
        const ans = await new Promise((resolve) => {
            this.runner.runJob(this.searchGenerator(iterator, batchSize, resolve));
        });
        const points = ans as Vector3[];
        this.startPoints = points;
    }

    private *searchGenerator(
        iterator: BlockLocationIterator,
        batchSize: number,
        resolve: (value: unknown) => void
    ) {
        const startType = "minecraft:emerald_block";
        const startPoints: Vector3[] = [];

        let data = iterator.next();
        let i = 0;

        while (!data.done) {
            const block = Dimensions.Overworld.getBlock(data.value);
            if (block?.typeId === startType && block.above()?.isAir) startPoints.push(data.value);

            i++;
            if (i >= batchSize) {
                i = 0;
                yield;
            }
            data = iterator.next();
        }
        resolve(startPoints);
    }
}
